package com.jsh.erp.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

@Component
public class SpringUtils implements ApplicationContextAware, PriorityOrdered {
    public static ApplicationContext ctx;

    public static <T> T getBean(ApplicationContext ctx, Class<T> clazz) {
        Map<String, T> beans = ctx.getBeansOfType(clazz);
        if (!CollectionUtils.isEmpty(beans)) {
            for (String keys : beans.keySet()) {
                return beans.get(keys);
            }
        }
        return null;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getBean(getApplicationContext(), clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String n) {
        return (T) getApplicationContext().getBean(n);
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    public static void publishEvent(ApplicationEvent event) {
        getApplicationContext().publishEvent(event);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.ctx = applicationContext;

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * SpringMvc下获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return request;
    }

    /**
     * SpringMvc下获取request
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        return response;
    }

    /**
     * SpringMvc下获取session
     *
     * @return
     */
    public static HttpSession getSession() {
        HttpSession session = getRequest().getSession();
        return session;
    }

}
